//LoginServlet.java
package com.ylaihui.web;

import com.ylaihui.pojo.User;
import com.ylaihui.service.UserService;
import com.ylaihui.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 查询数据库中是否存在用户
        User login = userService.login(new User(null, username, password, null));
        if (login == null) {
            System.out.println("登录失败");
            // 错误信息回显，将信息发送给 login.jsp
            req.setAttribute("username", username);
            req.setAttribute("msg", "用户名或密码错误！");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        } else {
            System.out.println("登录成功");
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }    }
}


